﻿using System;
using System.Collections.Generic;
using System.Text;
using LispInterpretor.HelperClasses;

namespace LispInterpretor.InBuiltProcedures
{
    public class Equals : Procedure
    {
        public override object Apply(params object[] args)
        {
            Check.IsTrue(args.Length >= 2, "Equals must compare something to something.");

            if (args[0] is IList<object>)
            {
                return DoListEquals(args);
            }
            else
            {
                return BasicObjectEquals(args);
            }
        }

        private static object BasicObjectEquals(object[] args)
        {
            object firstItem = args[0];

            for (int i = 1; i < args.Length; i++)
            {
                if (!firstItem.Equals(args[i]))
                {
                    return false;
                }
            }

            return true;
        }

        private bool DoListEquals(object[] args)
        {
            IList<object> firstCase = (IList<object>) args[0];

            for (int i = 1; i < args.Length; i++)
            {
                IList<object> item = (IList<object>)args[i];

                if (item.Count != firstCase.Count)
                {
                    return false;
                }

                for (int j = 0; j < item.Count; j++)
                {
                    if (!firstCase[j].Equals(item[j]))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
    }
}
